package com.tai.cobrapp.activity.crud;

import java.util.ArrayList;


import com.tai.cobrapp.R;


import com.tai.cobrapp.activity.EstablishmentSelectionActivity;
import com.tai.cobrapp.activity.LoginActivity;
import com.tai.cobrapp.activity.OptionsMenuActivity;
import com.tai.cobrapp.adapter.NewSurveyListAdapter;
import com.tai.cobrapp.backend.Backend;
import com.tai.cobrapp.model.DetalleRelevamiento;
import com.tai.cobrapp.model.Dispositivo;
import com.tai.cobrapp.model.Relevamiento;
import com.tai.cobrapp.model.Usuario;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager.LayoutParams;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

public class NewSurveyActivity extends ListActivity {
	private final static int EDIT_SURVEY_DIALOG = 1;
	private final static int EDIT_SURVEY_NAME_DIALOG = 2;
	private final static int SECURE_ON_BACK_DIALOG = 3;
	
	Relevamiento relevamiento = null;
	NewSurveyListAdapter adapter = null;
	Integer detalleListPosition = -1;
	ArrayList<DetalleRelevamiento> detRelList = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_surveys);
		
		Integer idEstab = null;
		if( this.getIntent().getExtras() != null ){
			idEstab = (Integer)this.getIntent().getExtras().get("idEstablecimiento");
		}
		
		ArrayList<Dispositivo> disp = Backend.getInstance().getActiveDispositivos(idEstab, this);
		detRelList = new ArrayList<DetalleRelevamiento>();
		DetalleRelevamiento  detRel = new DetalleRelevamiento();
		for (Integer i = 0; i < disp.size() ; i++){
			detRel = new DetalleRelevamiento((double)0, false, false, false, disp.get(i));
			detRelList.add(detRel);
		}
		java.util.Date utilDate = new java.util.Date();
		Editable nameRelev = new SpannableStringBuilder("Relevamiento");
		Editable dateUpd = new SpannableStringBuilder(utilDate.toString());
		relevamiento = new Relevamiento(Usuario.getUserInstance().getId(), dateUpd, (double)0, nameRelev, detRelList);
		//(Integer idUser, Editable dateUpdated, Double montoTotal, Editable name, ArrayList<DetalleRelevamiento> detalleRelevamiento)
		//Log.d("Click", relevamiento.getName());
		
		//Toast.makeText(this, relevamiento.getName(),  Toast.LENGTH_LONG).show();
		adapter = new NewSurveyListAdapter(this, detRelList);
		this.getListView().setAdapter(adapter);
		
		this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				// Agregar Custom Dialog para pedir lo necesario del dispositivo, luego cambiar los colores del item, vendido o no, etc
				//detalleAuxiliar = ((DetalleRelevamiento)adapter.getItem(position));
				detalleListPosition = position;
				
				showDialog(EDIT_SURVEY_DIALOG);
				return false;
			}
		});
		
	}
	@Override
	public void onBackPressed() {
		// Preguntar si esta seguro que desea salir, porque sino pierde el relevamiento
		showDialog(SECURE_ON_BACK_DIALOG);
		
		//super.onBackPressed();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_with_save, menu);
		return true;
	}
	@Override
	protected void onStop() {
		finish();
		super.onStop();
	}
	
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialogo;
		Dialog dialogoNameSurvey;
		
		switch(id){
		case EDIT_SURVEY_DIALOG:
			dialogo = new Dialog(this);
			dialogo.setContentView(R.layout.new_survey);
			dialogo.setTitle(R.string.edit_item);
			
			android.view.WindowManager.LayoutParams params = dialogo.getWindow().getAttributes();
			params.width = LayoutParams.MATCH_PARENT;
			params.height = LayoutParams.MATCH_PARENT;
			dialogo.getWindow().setAttributes(params);

			Button saveBtn = (Button)dialogo.findViewById(R.id.save_btn);
			Button cancelBtn = (Button)dialogo.findViewById(R.id.cancel_btn);
			final CheckBox fueVendido = (CheckBox)dialogo.findViewById(R.id.fue_vendido_chkbox);
			final CheckBox turnoManiana = (CheckBox)dialogo.findViewById(R.id.turno_maniana_chkbox);
			final CheckBox turnoTarde = (CheckBox)dialogo.findViewById(R.id.turno_tarde_chkbox);
			final EditText amountValue = (EditText)dialogo.findViewById(R.id.input_amount_edittext);
			final LinearLayout layerToHide = (LinearLayout)dialogo.findViewById(R.id.layer_to_hide);
						
			fueVendido.setChecked(detRelList.get(detalleListPosition).isVendido());
			turnoManiana.setChecked(detRelList.get(detalleListPosition).isTurnoManiana());
			turnoTarde.setChecked(detRelList.get(detalleListPosition).isTurnoTarde());
			amountValue.setText(Double.toString(detRelList.get(detalleListPosition).getMontoUnitario()));
			
			fueVendido.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener (){
				//android:visibility="gone"
				@Override
				public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
					layerToHide.setVisibility(isChecked?View.VISIBLE:View.INVISIBLE);
				}
				
			});

			android.view.View.OnClickListener saveDispListener = new Button.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// VALIDACIONES!!
					if(fueVendido.isChecked()){
						detRelList.get(detalleListPosition).setVendido(true);
						detRelList.get(detalleListPosition).setTurnoManiana(turnoManiana.isChecked());
						detRelList.get(detalleListPosition).setTurnoTarde(turnoTarde.isChecked());
						try {
							double doble = Double.parseDouble(amountValue.getText().toString());
							if(doble >= (double)0 && doble < (double)9999999){
								detRelList.get(detalleListPosition).setMontoUnitario(doble);
							}else {
								
							}
						} catch (NumberFormatException e) {
							  // doble did not contain a valid double
						}
					}
					else {
						detRelList.get(detalleListPosition).setVendido(false);
						detRelList.get(detalleListPosition).setTurnoManiana(false);
						detRelList.get(detalleListPosition).setTurnoTarde(false);
						detRelList.get(detalleListPosition).setMontoUnitario((double)0);
					}
					//Toast.makeText(NewSurveyActivity.this, "Survey item added", Toast.LENGTH_SHORT).show();
					dismissDialog(EDIT_SURVEY_DIALOG);

					adapter.SetSurveyList(detRelList);
					adapter.notifyDataSetChanged();
				}
			};
			
			android.view.View.OnClickListener cancelarListener = new Button.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dismissDialog(EDIT_SURVEY_DIALOG);										
				}
			};
			
			saveBtn.setOnClickListener(saveDispListener);
			cancelBtn.setOnClickListener(cancelarListener);
			
			return dialogo;
		case EDIT_SURVEY_NAME_DIALOG:
			dialogoNameSurvey = new Dialog(this);
			dialogoNameSurvey.setContentView(R.layout.new_survey_edit_name);
			//dialogoNameSurvey.setTitle(R.string.saving);
			
			android.view.WindowManager.LayoutParams params2 = dialogoNameSurvey.getWindow().getAttributes();
			params2.width = LayoutParams.MATCH_PARENT;
			params2.height = LayoutParams.MATCH_PARENT;
			dialogoNameSurvey.getWindow().setAttributes(params2);
			
			Button saveBtnSurveyName = (Button)dialogoNameSurvey.findViewById(R.id.new_survey_edit_name_save_btn);
			Button cancelBtnSurveyName = (Button)dialogoNameSurvey.findViewById(R.id.new_survey_edit_name_cancel_btn);
			final EditText surveyName = (EditText)dialogoNameSurvey.findViewById(R.id.new_survey_edit_name_edittext);
			
			android.view.View.OnClickListener saveSurveyNameListener = new Button.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(existeSurveyName(surveyName.getText())){
						Toast.makeText(NewSurveyActivity.this, surveyName.getText() + " " + getString(R.string.already_exists), Toast.LENGTH_SHORT).show();
						surveyName.setText("");
					}else{
						if(surveyName.getText().toString() == null || surveyName.getText().toString().isEmpty()){
							Toast.makeText(NewSurveyActivity.this, R.string.please_assing_survey_name, Toast.LENGTH_SHORT).show();
						}else{
							relevamiento.setName(surveyName.getText());
	
							Integer idRelevamiento = insertSurvey(relevamiento);
							// Insertar todos los DetalleRelevamiento
							insertSurveyDetails(detRelList, idRelevamiento);
							
							//Log.d("ID Relevamiento SAVE", idRelevamiento.toString());
							//Toast.makeText(LoginActivity.this, R.string.user_creation_successful, Toast.LENGTH_SHORT).show();
							dismissDialog(EDIT_SURVEY_NAME_DIALOG);
							
							Toast.makeText(NewSurveyActivity.this, R.string.survey_saved, Toast.LENGTH_SHORT).show();
							Intent i2 = new Intent(NewSurveyActivity.this, EstablishmentSelectionActivity.class);
							startActivity(i2);
						}
					}
					//Toast.makeText(NewSurveyActivity.this, "Survey item added", Toast.LENGTH_SHORT).show();

				}
			};
			
			android.view.View.OnClickListener cancelarSurveyNameListener = new Button.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dismissDialog(EDIT_SURVEY_NAME_DIALOG);										
				}
			};
			
			saveBtnSurveyName.setOnClickListener(saveSurveyNameListener);
			cancelBtnSurveyName.setOnClickListener(cancelarSurveyNameListener);
			
			return dialogoNameSurvey;
		case SECURE_ON_BACK_DIALOG:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
	        builder.setMessage(R.string.are_you_sure_to_exit)
	               .setPositiveButton(R.string.exit, new DialogInterface.OnClickListener() {
	                   public void onClick(DialogInterface dialog, int id) {
	                	   Intent i = new Intent(NewSurveyActivity.this, OptionsMenuActivity.class);
	                	   startActivity(i);
	                   }
	               })
	               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
	                   public void onClick(DialogInterface dialog, int id) {
	                       // User cancelled the dialog
	                   }
	               });
	        // Create the AlertDialog object and return it
	        return builder.create();
		default:
			return super.onCreateDialog(id);
		}
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch(item.getItemId()){
		case R.id.main_menu:
			Intent i = new Intent(this, OptionsMenuActivity.class);
			startActivity(i);
			break;
		case R.id.log_out:
			Intent i2 = new Intent(this, LoginActivity.class);
			startActivity(i2);
			break;
		case R.id.save:
			// SALVAR EL RELEVAMIENTO EN LA BASE DE DATOS
			// ARMAR VENTANA PARA PREGUNTAR NOMBRE DEL RELEVAMIENTO, LUEGO CHEQUEAR QUE NO EXISTA ESE NOMBRE
			showDialog(EDIT_SURVEY_NAME_DIALOG);
			
			//this.relevamiento
			//Intent i3 = new Intent(this, LoginActivity.class);
			//startActivity(i3);
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	public boolean existeSurveyName(Editable surveyName){
		//return false;
		if(Backend.getInstance().existeRelevamiento(this, surveyName)){
			return true;
		}else{
			return false;
		}
	}
	public Integer insertSurvey(Relevamiento relev){
		return Backend.getInstance().insertSurvey(this, relev);
		//DatabaseHelper.getDatabaseInstance(this).insertarUsuario(u);
	}
	public void insertSurveyDetails(ArrayList<DetalleRelevamiento> detRelev, Integer idRelev){
		Backend.getInstance().insertSurveyDetail(this, detRelev, idRelev);
		//DatabaseHelper.getDatabaseInstance(this).insertarUsuario(u);
	}
}
